//
//  IDCardViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2019/2/19.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit
import AipOcrSdk
import IDLFaceSDK

class IDCardViewController: UIViewController, SegueHandlerType {

    enum SegueIdentifier: String {
        case nextSegue
    }
    
    @IBOutlet weak var nameTextField: UITextField!
    
    @IBOutlet weak var identifierTextField: UITextField!
    
    @IBOutlet weak var handButton: UIButton!
    
    var idcardFrontImg: String?               //身份证正面照片（照片）
    var idcardBackImg: String?               //身份证背面照片（国徽）
    var idcardHandImg: String?               //手持身份证照片
    
    var drivingLicenseFn: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    // 身份证正面照
    @IBAction func idcardOCROnlineFront(_ sender: UIButton) {
        let vc = AipCaptureCardVC.viewController(with: .localIdCardFont) { [weak self] image in

            guard let img = image else {
                XHProgressHUD.showError("图片为空")
                return
            }
            
            self?.dismiss(animated: true)
            
            sender.setImage(img, for: .normal)
            
            //上传图片
            User.uploadFile(img) { [weak self] imagePath in
                self?.idcardFrontImg = imagePath
            }
            
            //识别图片
            AipOcrService.shard().detectIdCardFront(from: img, withOptions: nil, successHandler: { result in
                self?.getImageInfo(a: result as Any)
            }, failHandler: { (error) in
                XHProgressHUD.showError("图片识别失败，请重新上传!")
            })
        }
        
        present(vc!, animated: true)
    }
    
    //身份证反面
    @IBAction func idcardOCROnlineBack(_ sender: UIButton) {
        let vc = AipCaptureCardVC.viewController(with: .localIdCardBack) { [weak self] image in
            
            guard let img = image else {
                XHProgressHUD.showError("图片为空")
                return
            }
            
            self?.dismiss(animated: true)
            
            sender.setImage(img, for: .normal)
            
            //上传图片
            User.uploadFile(img) { [weak self] imagePath in
                self?.idcardBackImg = imagePath
            }
        }
        
        present(vc!, animated: true)
    }
    
    //手持身份证
    @IBAction func personAndImage(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            
            present(cameraPicker, animated: true)
        } else {
            showError("不支持拍照")
        }
    }
    
    @IBAction func next(_ sender: UIButton) {
        
        guard let front = idcardFrontImg else {
            self.showError("请您上传身份证正面照片(1000)")
            return
        }
        
        guard let back = idcardBackImg else {
            self.showError("请您上传身份证反面照片(1001)")
            return
        }
        
        guard let hand = idcardHandImg else {
            self.showError("请您上传手持身份证照片(1002)")
            return
        }
        
        guard let name = nameTextField.text else {
            self.showError("请您正确填写证件姓名(1005)")
            return
        }
        
        guard let id = self.identifierTextField.text else {
            self.showError("请您正确填写证件号码(1006)")
            return
        }
        
        XHProgressHUD.showStatusInfo("正在识别认证中")
        User.AuthenticationIDCard(
            idcardFrontImg: front,
            idcardBackImg: back,
            idcardHandImg: hand,
            realName: name,
            idcardNumber: id,
            success: { [weak self] data in
                
                guard let self = self else {
                    return
                }
                
                self.drivingLicenseFn = data?.drivingLicenseFn
                
                XHProgressHUD.dismiss()
                if let user = User.info() {
                    user.certStep = 1
                    user.username = name
                    User.saveUserInfo(user)
                    self.slipViewController?.menuViewController?.refresh()
                    //认证成功
                    
                    self.performSegue(.nextSegue, sender: nil)
                }
        }) { [weak self] error in
            XHProgressHUD.dismiss()
            self?.showError(error)
        }
    }
    
    //图片分析成功
    func getImageInfo(a:Any) {
        DispatchQueue.main.async {
            //需要提取姓名,身份证号
            let some = (((a as AnyObject)["words_result"] as? [String : Any])!["姓名"] as AnyObject)["words"]
            let ID = (((a as AnyObject)["words_result"] as? [String : Any])!["公民身份号码"] as AnyObject)["words"]
            self.nameTextField.text = some as? String
            self.identifierTextField.text = ID as? String
        }
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        switch segueIdentifier(forSegue: segue) {
        case .nextSegue:
            if let vc = segue.destination as? DrivingLicenseViewController {
                vc.drivingLicenseFn = drivingLicenseFn
            }
        }
    }

}

extension IDCardViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        self.dismiss(animated: true)
        
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        
        handButton.setImage(image, for: .normal)
        
        //上传图片
        User.uploadFile(image) { [weak self] imagePath in
            self?.idcardHandImg = imagePath
        }
    }
}
